#pragma once

#include <functional>

#include "Socket.hpp"

#include "Log.hpp"
#include "InetAddr.hpp"

using namespace socket_ns;

static const uint16_t gport = 8888;

using service_t = std::function<std::string(std::string &requeststr)>;

class TcpServer
{
public:
    TcpServer(service_t service, uint16_t port = gport)
        : _port(port),
          _listensockfd(std::make_shared<TcpSocket>()),
          _isrunning(false),
          _service(service)
    {
        _listensockfd->BuildListenSocket(_port);
    }

    class ThreadData
    {
    public:
        ThreadData(SockPtr sockfd, TcpServer *self, const InetAddr &addr)
            : _sockfd(sockfd), _self(self), _addr(addr)
        {
        }

    public:
        SockPtr _sockfd;
        TcpServer *_self;
        InetAddr _addr;
    };

    void Loop()
    {
        // signal(SIGCHLD, SIG_IGN);
        _isrunning = true;
        while (_isrunning)
        {
            // 4.获取新连接
            InetAddr client;
            SockPtr newsock = _listensockfd->Accepter(&client);
            if (newsock == nullptr)
            {
                LOG(WARNING, "accept error\n");
                continue;
            }

            LOG(INFO, "get a new link, client info: %s, sockfd is: %d\n", client.AddrStr().c_str(), newsock->Sockfd());

            // version 2 -- 多线程版本 -- 不能关闭fd。
            pthread_t tid;

            ThreadData *td = new ThreadData(newsock, this, client);
            pthread_create(&tid, nullptr, Excute, td); // 新线程分离
        }
        _isrunning = false;
    }

    static void *Excute(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args);

        std::string requeststr;
        ssize_t n = td->_sockfd->Recv(&requeststr); // 我们后面不做请求的分离。我们认为我们读到的是一个完整的请求 ---bug
        if (n > 0)
        {
            std::string response = td->_self->_service(requeststr);
            td->_sockfd->Send(response);
        }

        td->_sockfd->Close();
        delete td;
        return nullptr;
    }

    ~TcpServer()
    {
    }

private:
    uint16_t _port;
    SockPtr _listensockfd;
    bool _isrunning;
    service_t _service;
};